import React from 'react';
import { Alert, Button, Typography, Space, Divider, Spin, Result } from 'antd';
import { 
    ExclamationCircleOutlined, 
    ReloadOutlined,
    InfoCircleOutlined,
    WarningOutlined,
    CloseCircleOutlined 
} from '@ant-design/icons';
import { ApiError } from '../utils/request';

const { Text, Paragraph } = Typography;

interface ErrorDisplayProps {
    error: ApiError | string | null;
    onRetry?: () => void;
    onDismiss?: () => void;
    showDetails?: boolean;
    size?: 'small' | 'default' | 'large';
    style?: React.CSSProperties;
    variant?: 'alert' | 'result' | 'inline';
    loading?: boolean;
    retryCount?: number;
    maxRetries?: number;
}

// 根据错误类型获取对应的图标和颜色
const getErrorType = (error: ApiError | string) => {
    if (typeof error === 'string') {
        return {
            type: 'error' as const,
            icon: <CloseCircleOutlined />,
            title: '错误'
        };
    }

    const status = error.status;
    
    if (!status) {
        return {
            type: 'error' as const,
            icon: <CloseCircleOutlined />,
            title: '网络错误'
        };
    }

    if (status >= 500) {
        return {
            type: 'error' as const,
            icon: <ExclamationCircleOutlined />,
            title: '服务器错误'
        };
    }

    if (status >= 400) {
        return {
            type: 'warning' as const,
            icon: <WarningOutlined />,
            title: '请求错误'
        };
    }

    return {
        type: 'info' as const,
        icon: <InfoCircleOutlined />,
        title: '提示'
    };
};

// 获取用户友好的错误描述
const getErrorDescription = (error: ApiError | string): string => {
    if (typeof error === 'string') {
        return error;
    }

    const status = error.status;
    
    // 根据状态码提供更详细的说明
    switch (status) {
        case 408:
        case 504:
            return `${error.message}，这通常是由于网络延迟或服务器负载过高导致的，请稍后重试。`;
        case 500:
            return `${error.message}，服务器遇到了内部错误，我们已记录此问题，请稍后重试。`;
        case 502:
        case 503:
            return `${error.message}，服务暂时不可用，可能正在进行维护，请稍后重试。`;
        case 400:
            return `${error.message}，请检查输入的参数是否正确。`;
        case 401:
            return `${error.message}，请重新登录后再试。`;
        case 403:
            return `${error.message}，请联系管理员获取相应权限。`;
        case 404:
            return `${error.message}，请确认访问的资源是否存在。`;
        default:
            return error.message;
    }
};

const ErrorDisplay: React.FC<ErrorDisplayProps> = ({
    error,
    onRetry,
    onDismiss,
    showDetails = false,
    size = 'default',
    style,
    variant = 'alert',
    loading = false,
    retryCount = 0,
    maxRetries = 2
}) => {
    if (!error) {
        return null;
    }

    const errorInfo = getErrorType(error);
    const description = getErrorDescription(error);
    const canRetry = typeof error === 'object' && error.retry;

    const actions = [];
    
    if (onRetry && (canRetry || typeof error === 'string')) {
        const isRetryDisabled = retryCount >= maxRetries;
        actions.push(
            <Button
                key="retry"
                type="primary"
                size={size === 'small' ? 'small' : 'middle'}
                icon={loading ? <Spin size="small" /> : <ReloadOutlined />}
                onClick={onRetry}
                loading={loading}
                disabled={isRetryDisabled}
            >
                {isRetryDisabled ? `已重试${retryCount}次` : loading ? '重试中...' : retryCount > 0 ? `重试(${retryCount}/${maxRetries})` : '重试'}
            </Button>
        );
    }

    if (onDismiss) {
        actions.push(
            <Button
                key="dismiss"
                size={size === 'small' ? 'small' : 'middle'}
                onClick={onDismiss}
            >
                关闭
            </Button>
        );
    }

    // Result variant for full-page errors
    if (variant === 'result') {
        return (
            <Result
                status={errorInfo.type === 'error' ? 'error' : errorInfo.type === 'warning' ? 'warning' : 'info'}
                title={errorInfo.title}
                subTitle={description}
                extra={actions}
                style={style}
            >
                {showDetails && typeof error === 'object' && error.details && (
                    <div style={{ textAlign: 'left', maxWidth: 600, margin: '0 auto' }}>
                        <Divider />
                        <details>
                            <summary style={{ cursor: 'pointer', color: '#666' }}>
                                <Text type="secondary">技术详情</Text>
                            </summary>
                            <div style={{ 
                                marginTop: 8, 
                                padding: '12px', 
                                backgroundColor: '#f5f5f5', 
                                borderRadius: 6,
                                fontFamily: 'Consolas, Monaco, monospace',
                                fontSize: 13,
                                color: '#666',
                                border: '1px solid #d9d9d9'
                            }}>
                                <div>状态码: <strong>{error.status || 'N/A'}</strong></div>
                                <div style={{ marginTop: 4 }}>详细信息: {error.details}</div>
                            </div>
                        </details>
                    </div>
                )}
            </Result>
        );
    }

    // Inline variant for compact display  
    if (variant === 'inline') {
        return (
            <div style={{ 
                display: 'inline-flex', 
                alignItems: 'center', 
                gap: 8,
                padding: '4px 8px',
                backgroundColor: errorInfo.type === 'error' ? '#fff2f0' : '#fffbe6',
                border: `1px solid ${errorInfo.type === 'error' ? '#ffccc7' : '#ffe58f'}`,
                borderRadius: 4,
                fontSize: size === 'small' ? 12 : 14,
                ...style 
            }}>
                {errorInfo.icon}
                <Text type={errorInfo.type === 'error' ? 'danger' : 'warning'}>
                    {typeof error === 'string' ? error : error.message}
                </Text>
                {actions.length > 0 && <Space size={4}>{actions}</Space>}
            </div>
        );
    }

    return (
        <Alert
            message={
                <Space align="center">
                    {errorInfo.icon}
                    <Text strong>{errorInfo.title}</Text>
                </Space>
            }
            description={
                <div>
                    <Paragraph style={{ marginBottom: showDetails ? 16 : 0 }}>
                        {description}
                    </Paragraph>
                    
                    {showDetails && typeof error === 'object' && error.details && (
                        <>
                            <Divider style={{ margin: '12px 0' }} />
                            <details>
                                <summary style={{ cursor: 'pointer', color: '#666' }}>
                                    <Text type="secondary">技术详情</Text>
                                </summary>
                                <div style={{ 
                                    marginTop: 8, 
                                    padding: '8px 12px', 
                                    backgroundColor: '#f5f5f5', 
                                    borderRadius: 4,
                                    fontFamily: 'monospace',
                                    fontSize: 12,
                                    color: '#666'
                                }}>
                                    状态码: {error.status || 'N/A'}<br />
                                    详细信息: {error.details}
                                </div>
                            </details>
                        </>
                    )}
                </div>
            }
            type={errorInfo.type}
            showIcon={false}
            action={actions.length > 0 ? <Space>{actions}</Space> : undefined}
            style={style}
        />
    );
};

export default ErrorDisplay;